<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>SpringMVC | Cying</title><meta name="keywords" content="JavaEE"><meta name="author" content="Cying-承影"><meta name="copyright" content="Cying-承影"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="SpringMVC  一、MVC 概述1.1.什么是 MVC  MVC是模型(Model)、视图(View)、 控制器(Controller)的简写， 是一种软件设计规范。 是将业务逻辑、数据、显示分离的方法来组织代码。 MVC主要作用是降低了视图与业务逻辑间的双向偶合。 MVC不是一种设计模式，MVC是-种架构模式。当然不同的MVC存在差异。     Model (模型) :数据模型，提供要展示">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringMVC">
<meta property="og:url" content="http://cyingk.github.io/2020/02/16/SpringMVC/index.html">
<meta property="og:site_name" content="Cying">
<meta property="og:description" content="SpringMVC  一、MVC 概述1.1.什么是 MVC  MVC是模型(Model)、视图(View)、 控制器(Controller)的简写， 是一种软件设计规范。 是将业务逻辑、数据、显示分离的方法来组织代码。 MVC主要作用是降低了视图与业务逻辑间的双向偶合。 MVC不是一种设计模式，MVC是-种架构模式。当然不同的MVC存在差异。     Model (模型) :数据模型，提供要展示">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=790255512,3591398303&fm=26&gp=0.jpg">
<meta property="article:published_time" content="2020-02-16T10:01:31.000Z">
<meta property="article:modified_time" content="2020-07-03T16:22:26.000Z">
<meta property="article:author" content="Cying-承影">
<meta property="article:tag" content="JavaEE">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=790255512,3591398303&fm=26&gp=0.jpg"><link rel="shortcut icon" href="/img/favicon.ico"><link rel="canonical" href="http://cyingk.github.io/2020/02/16/SpringMVC/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.clarity.ms"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>(function(c,l,a,r,i,t,y){
    c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
    t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
    y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", "4zndahq92q");</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: 'days',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"Traditional Chinese Activated Manually","cht_to_chs":"Simplified Chinese Activated Manually","day_to_night":"Dark Mode Activated Manually","night_to_day":"Light Mode Activated Manually","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isanchor: false
};

const saveToLocal = {
  // ttl 單位是 天
  set: function setWithExpiry(key, value, ttl) {
    if (ttl === 0) return
    const now = new Date()
    const expiryDay = ttl * 86400000
    const item = {
      value: value,
      expiry: now.getTime() + expiryDay,
    }
    localStorage.setItem(key, JSON.stringify(item))
  },

  get: function getWithExpiry(key) {
    const itemStr = localStorage.getItem(key)

    if (!itemStr) {
      return undefined
    }
    const item = JSON.parse(itemStr)
    const now = new Date()

    if (now.getTime() > item.expiry) {
      localStorage.removeItem(key)
      return undefined
    }
    return item.value
  }
}

// https://stackoverflow.com/questions/16839698/jquery-getscript-alternative-in-native-javascript
const getScript = url => new Promise((resolve, reject) => {
  const script = document.createElement('script')
  script.src = url
  script.async = true
  script.onerror = reject
  script.onload = script.onreadystatechange = function() {
    const loadState = this.readyState
    if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
    script.onload = script.onreadystatechange = null
    resolve()
  }
  document.head.appendChild(script)
})</script><script id="config_change">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2020-07-04 00:22:26'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(function () {  window.activateDarkMode = function () {
    document.documentElement.setAttribute('data-theme', 'dark')
    if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
    }
  }
  window.activateLightMode = function () {
    document.documentElement.setAttribute('data-theme', 'light')
   if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
    }
  }
  const autoChangeMode = '1'
  const t = saveToLocal.get('theme')
  if (autoChangeMode === '1') {
    const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
    const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
    const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
    const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified
    if (t === undefined) {
      if (isLightMode) activateLightMode()
      else if (isDarkMode) activateDarkMode()
      else if (isNotSpecified || hasNoSupport) {
        const now = new Date()
        const hour = now.getHours()
        const isNight = hour <= 6 || hour >= 18
        isNight ? activateDarkMode() : activateLightMode()
      }
      window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
        if (saveToLocal.get('theme') === undefined) {
          e.matches ? activateDarkMode() : activateLightMode()
        }
      })
    } else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else if (autoChangeMode === '2') {
    const now = new Date()
    const hour = now.getHours()
    const isNight = hour <= 6 || hour >= 18
    if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
    else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else {
    if (t === 'dark') activateDarkMode()
    else if (t === 'light') activateLightMode()
  }const asideStatus = saveToLocal.get('aside-status')
if (asideStatus !== undefined) {
   if (asideStatus === 'hide') {
     document.documentElement.classList.add('hide-aside')
   } else {
     document.documentElement.classList.remove('hide-aside')
   }
}const fontSizeVal = saveToLocal.get('global-font-size')
if (fontSizeVal !== undefined) {
  document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
}})()</script><meta name="generator" content="Hexo 5.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">Loading...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="/img/avatar.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">23</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">12</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">Categories</div><div class="length-num">3</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> Categories</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://5b0988e595225.cdn.sohucs.com/images/20190831/84729f5c5bb346208416445feb485df6.jpeg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Cying</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> Categories</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">SpringMVC</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2020-02-16T10:01:31.000Z" title="Created 2020-02-16 18:01:31">2020-02-16</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2020-07-03T16:22:26.000Z" title="Updated 2020-07-04 00:22:26">2020-07-04</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Note/">Note</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">Word count:</span><span class="word-count">2.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">Reading time:</span><span>11min</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><html><head></head><body><h1 style="
           font-size: 60px;
           font-weight: bolder;
           border: none;
           "><center>SpringMVC</center></h1>

<h1 id="一、MVC-概述"><a href="#一、MVC-概述" class="headerlink" title="一、MVC 概述"></a>一、MVC 概述</h1><h2 id="1-1-什么是-MVC"><a href="#1-1-什么是-MVC" class="headerlink" title="1.1.什么是 MVC"></a>1.1.什么是 MVC</h2><blockquote>
<ul>
<li>MVC是模型(<code>Model</code>)、视图(View)、 控制器(Controller)的简写， 是一种软件设计规范。</li>
<li>是将业务逻辑、数据、显示分离的方法来组织代码。</li>
<li>MVC主要作用是降低了视图与业务逻辑间的双向偶合。</li>
<li>MVC不是一种设计模式，MVC是-种架构模式。当然不同的MVC存在差异。</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li><code>Model</code> (模型) :数据模型，提供要展示的数据，因此包含数据和行为，可以认为是领域模型或<code>JavaBean</code>组件(包含数据和行为)，不过现在-般都分离开来: <code>Value Object</code> (数据<code>Dao</code>)和服务层(行为<code>Service</code>) 。也就是模型提供了模型数据查询和模型数据的状态更新等功能，包括数据和业务。</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li><code>View</code> (视图) :负责进行模型的展示，-般就是我们见到的用户界面，客户想看到的东西。</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li><code>Controller</code> (控制器) :接收用户请求，委托给模型进行处理(状态改变)， 处理完毕后把返回的<br>模型数据返回给视图，由视图负责展示。也就是说控制器做了个调度员的工作。</li>
</ul>
</blockquote>
<p><a href="C:%5CUsers%5CCying%5COneDrive%5CTypora%5CFrame%5Cimg%5CSpringMVC%5CModel1.png" data-fancybox="group" data-caption="Model1时代" class="fancybox"><img alt="Model1时代" title="Model1时代" data-src="C:%5CUsers%5CCying%5COneDrive%5CTypora%5CFrame%5Cimg%5CSpringMVC%5CModel1.png" class="lazyload"></a></p>
<center><strong>Model 1 时代</strong></center><hr>

<p><a href="C:%5CUsers%5CCying%5COneDrive%5CTypora%5CFrame%5Cimg%5CSpringMVC%5CModel2.png" data-fancybox="group" data-caption="Model2" class="fancybox"><img alt="Model2" title="Model2" data-src="C:%5CUsers%5CCying%5COneDrive%5CTypora%5CFrame%5Cimg%5CSpringMVC%5CModel2.png" class="lazyload"></a></p>
<center><strong>Model 2 时代</strong></center><hr>

<h2 id="1-2-导入依赖"><a href="#1-2-导入依赖" class="headerlink" title="1.2.导入依赖"></a>1.2.导入依赖</h2><p><strong>pom.xml</strong></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">xml</div></div><figure class="highlight xml"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"><!--?xml version="1.0" encoding="UTF-8"?--></span></span><br><span class="line"><span class="tag"><<span class="name">project</span> <span class="attr">xmlns</span>=<span class="string">"http://maven.apache.org/POM/4.0.0"</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">modelVersion</span>></span>4.0.0<span class="tag">< /<span class="attr">modelVersion</span>></span></span><br><span class="line"></span><br><span class="line">    <span class="tag"><<span class="name">groupId</span>></span>org.cying.study<span class="tag">< /<span class="attr">groupId</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">artifactId</span>></span>SpringMVC<span class="tag">< /<span class="attr">artifactId</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">version</span>></span>1.0-SNAPSHOT<span class="tag">< /<span class="attr">version</span>></span></span><br><span class="line"></span><br><span class="line">    <span class="tag"><<span class="name">dependencies</span>></span></span><br><span class="line">        <span class="tag"><<span class="name">dependency</span>></span></span><br><span class="line">            <span class="tag"><<span class="name">groupId</span>></span>junit<span class="tag">< /<span class="attr">groupId</span>></span></span><br><span class="line">            <span class="tag"><<span class="name">artifactId</span>></span>junit<span class="tag">< /<span class="attr">artifactId</span>></span></span><br><span class="line">            <span class="tag"><<span class="name">version</span>></span>4.12<span class="tag">< /<span class="attr">version</span>></span></span><br><span class="line">        <span class="tag">< /<span class="attr">dependency</span>></span></span><br><span class="line">        <span class="tag"><<span class="name">dependency</span>></span></span><br><span class="line">            <span class="tag"><<span class="name">groupId</span>></span>org.springframework<span class="tag">< /<span class="attr">groupId</span>></span></span><br><span class="line">            <span class="tag"><<span class="name">artifactId</span>></span>spring-webmvc<span class="tag">< /<span class="attr">artifactId</span>></span></span><br><span class="line">            <span class="tag"><<span class="name">version</span>></span>5.1.9.RELEASE<span class="tag">< /<span class="attr">version</span>></span></span><br><span class="line">        <span class="tag">< /<span class="attr">dependency</span>></span></span><br><span class="line">        <span class="tag"><<span class="name">dependency</span>></span></span><br><span class="line">            <span class="tag"><<span class="name">groupId</span>></span>javax.servlet<span class="tag">< /<span class="attr">groupId</span>></span></span><br><span class="line">            <span class="tag"><<span class="name">artifactId</span>></span>servlet-api<span class="tag">< /<span class="attr">artifactId</span>></span></span><br><span class="line">            <span class="tag"><<span class="name">version</span>></span>2.5<span class="tag">< /<span class="attr">version</span>></span></span><br><span class="line">        <span class="tag">< /<span class="attr">dependency</span>></span></span><br><span class="line">    <span class="tag">< /<span class="attr">dependencies</span>></span></span><br><span class="line"><span class="tag">< /<span class="attr">project</span>></span></span><br></pre></td></tr></tbody></table></figure></div>

<h2 id="1-3-特点"><a href="#1-3-特点" class="headerlink" title="1.3.特点"></a>1.3.特点</h2><blockquote>
<ul>
<li>轻量级，简单易学</li>
<li>高效,基于请求响应的 <code>MVC</code> 框架</li>
<li>与 <code>Spring</code>兼容性好，无缝结合</li>
<li>约定优于配置</li>
<li>功能强大:  <code>RESTful</code>、数据验证、格式化、本地化、主题等</li>
<li>简洁灵活</li>
</ul>
</blockquote>
<h2 id="1-4-中心控制器"><a href="#1-4-中心控制器" class="headerlink" title="1.4.中心控制器"></a>1.4.中心控制器</h2><blockquote>
<ul>
<li><code>Spring</code> 的 <code>web</code> 框架围绕 <code>DispatcherServlet</code> 设计。<code>DispatcherServlet</code> 的作用是将请求分发到不同的处理器。从 <code>Spring 2.5</code> 开始,使用 <code>Java 5</code> 或者以上版本的用户可以采用基于注解的 <code>controller</code>声明方式。</li>
</ul>
</blockquote>
<h2 id="1-5-原理"><a href="#1-5-原理" class="headerlink" title="1.5.原理"></a>1.5.原理</h2><blockquote>
<ul>
<li>当发起请求时被前置的控制器拦截到请求，根据请求参数生成代理请求,找到请求对应的实际控制器，控制器处理请求，创建数据模型，访问数据库，将模型响应给中心控制器，控制器使用模型与视图渲染视图结果，将结果返回给中心控制器，再将结果返回给请求者。</li>
</ul>
</blockquote>
<p><a href="C:%5CUsers%5CCying%5COneDrive%5CTypora%5CFrame%5Cimg%5CSpringMVC%5Cyuanli.png" data-fancybox="group" data-caption="yuanli" class="fancybox"><img alt="yuanli" title="yuanli" data-src="C:%5CUsers%5CCying%5COneDrive%5CTypora%5CFrame%5Cimg%5CSpringMVC%5Cyuanli.png" class="lazyload"></a></p>
<p><a href="C:%5CUsers%5CCying%5COneDrive%5CTypora%5CFrame%5Cimg%5CSpringMVC%5Cyuanli2.png" data-fancybox="group" data-caption="yuanli2" class="fancybox"><img alt="yuanli2" title="yuanli2" data-src="C:%5CUsers%5CCying%5COneDrive%5CTypora%5CFrame%5Cimg%5CSpringMVC%5Cyuanli2.png" class="lazyload"></a></p>
<h2 id="1-6-执行流程分析"><a href="#1-6-执行流程分析" class="headerlink" title="1.6.执行流程分析"></a>1.6.执行流程分析</h2><blockquote>
<ul>
<li><code>DispatcherServlet</code>表示前置控制器，是整个SpringMVC的控制中心。用户发出请求，<code>DispatcherServlet</code>接收请求并拦截请求。</li>
<li><code>HandlerMapping</code>为处理器映射。<code>DispatcherServlet</code>调用<code>HandlerMapping</code>，<code>HandlerMapping</code>根据请求<code>url</code>查找<code>Handler</code>。</li>
<li><code>HandlerExecution</code>表示具体的<code>Handler</code>，其主要作用是根据<code>url</code>查找控制器，如上<code>url</code>被查找控制器为: <code>hello</code>。</li>
<li><code>HandlerExecution</code>将解析后的信息传递给<code>DispatcherServlet</code>，如解析控制器映射等。</li>
<li><code>HandlerAdapter</code>表示处理器适配器，其按照特定的规则去执行<code>Handler</code>。</li>
<li><code>Handler</code>让具体的<code>Controller</code>执行。</li>
<li><code>Controller</code>将具体的执行信息返回给<code>HandlerAdapter</code>，如<code>ModelAndView</code>。</li>
<li><code>HandlerAdapter</code>将视图逻辑名或模型传递给<code>DispatcherServlet</code>。</li>
<li><code>DispatcherServlet</code>调用视图解析器(<code>ViewResolver</code>)来解析<code>HandlerAdapter</code>传递的逻辑视图名。</li>
<li>视图解析器将解析的逻辑视图名传给<code>DispatcherServlet</code>。</li>
<li><code>DispatcherServlet</code>根据视图解析器解析的视图结果，调用具体的视图。</li>
<li>最终视图呈现给用户。</li>
</ul>
</blockquote>
<h1 id="二、具体实现"><a href="#二、具体实现" class="headerlink" title="二、具体实现"></a>二、具体实现</h1><p><strong>在 web.xml 注册 DispatcherServlet</strong></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">xml</div></div><figure class="highlight xml"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"><!--?xml version="1.0" encoding="UTF-8"?--></span></span><br><span class="line"><span class="tag"><<span class="name">web-app</span> <span class="attr">xmlns</span>=<span class="string">"http://xmlns.jcp.org/xml/ns/javaee"</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"</span></span></span><br><span class="line"><span class="tag">         <span class="attr">version</span>=<span class="string">"4.0"</span>></span></span><br><span class="line"></span><br><span class="line">    <span class="tag"><<span class="name">servlet</span>></span></span><br><span class="line">        <span class="tag"><<span class="name">servlet-name</span>></span>springmvc<span class="tag">< /<span class="attr">servlet-name</span>></span></span><br><span class="line">        <span class="tag"><<span class="name">servlet-class</span>></span>org.springframework.web.servlet.DispatcherServlet<span class="tag">< /<span class="attr">servlet-class</span>></span></span><br><span class="line"></span><br><span class="line">        <span class="tag"><<span class="name">init-param</span>></span></span><br><span class="line">            <span class="tag"><<span class="name">param-name</span>></span>contextConfigLocation<span class="tag">< /<span class="attr">param-name</span>></span></span><br><span class="line">            <span class="tag"><<span class="name">param-value</span>></span>classpath:springmvc-servlet.xml<span class="tag">< /<span class="attr">param-value</span>></span></span><br><span class="line">        <span class="tag">< /<span class="attr">init-param</span>></span></span><br><span class="line"></span><br><span class="line">        <span class="tag"><<span class="name">load-on-startup</span>></span>1<span class="tag">< /<span class="attr">load-on-startup</span>></span></span><br><span class="line"></span><br><span class="line">    <span class="tag">< /<span class="attr">servlet</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">servlet-mapping</span>></span></span><br><span class="line">        <span class="tag"><<span class="name">servlet-name</span>></span>springmvc<span class="tag">< /<span class="attr">servlet-name</span>></span></span><br><span class="line">        <span class="tag"><<span class="name">url-pattern</span>></span>/<span class="tag">< /<span class="attr">url-pattern</span>></span></span><br><span class="line">    <span class="tag">< /<span class="attr">servlet-mapping</span>></span></span><br><span class="line"></span><br><span class="line"><span class="tag">< /<span class="attr">web-app</span>></span></span><br></pre></td></tr></tbody></table></figure></div>

<p><strong>在 resources 新建 springmvc-servlet.xml</strong></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">xml</div></div><figure class="highlight xml"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"><!--?xml version="1.0" encoding="UTF-8"?--></span></span><br><span class="line"><span class="tag"><<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:context</span>=<span class="string">"http://www.springframework.org/schema/context"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:mvc</span>=<span class="string">"http://www.springframework.org/schema/mvc"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/context</span></span></span><br><span class="line"><span class="tag"><span class="string">        https://www.springframework.org/schema/context/spring-context.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/mvc</span></span></span><br><span class="line"><span class="tag"><span class="string">        https://www.springframework.org/schema/mvc/spring-mvc.xsd"</span>></span></span><br><span class="line">    </span><br><span class="line">    <span class="comment"><!-- 自动扫描包，让指定包下的注解生效,由IOC容器统一管理 --></span></span><br><span class="line">    <span class="tag"><<span class="name">context:component-scan</span> <span class="attr">base-package</span>=<span class="string">"包路径"</span>/></span></span><br><span class="line"></span><br><span class="line">    <span class="tag"><<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"</span>/></span></span><br><span class="line">    <span class="tag"><<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"</span>/></span></span><br><span class="line"></span><br><span class="line">    <span class="tag"><<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.web.servlet.view.InternalResourceViewResolver"</span> <span class="attr">id</span>=<span class="string">"InternalResourceViewResolver"</span>></span></span><br><span class="line">        <span class="comment"><!--前缀--></span></span><br><span class="line">        <span class="tag"><<span class="name">property</span> <span class="attr">name</span>=<span class="string">"prefix"</span> <span class="attr">value</span>=<span class="string">"/WEB-INF/jsp/"</span>/></span></span><br><span class="line">        <span class="comment"><!--后缀--></span></span><br><span class="line">        <span class="tag"><<span class="name">property</span> <span class="attr">name</span>=<span class="string">"suffix"</span> <span class="attr">value</span>=<span class="string">".jsp"</span>/></span></span><br><span class="line">    <span class="tag">< /<span class="attr">bean</span>></span></span><br><span class="line"></span><br><span class="line"><span class="tag">< /<span class="attr">beans</span>></span></span><br></pre></td></tr></tbody></table></figure></div>

<h2 id="2-1-原始方法实现"><a href="#2-1-原始方法实现" class="headerlink" title="2.1.原始方法实现"></a>2.1.原始方法实现</h2><p><strong>在 <code>springmvc-serlvet.xml 配置</code>Spring Bean`，指向实体类</strong></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">xml</div></div><figure class="highlight xml"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag"><<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"实体类全路径"</span> <span class="attr">id</span>=<span class="string">"/外界访问路径"</span>/></span></span><br></pre></td></tr></tbody></table></figure></div>

<p><strong>书写实体类</strong></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.web.servlet.ModelAndView;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.servlet.mvc.Controller;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletRequest;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletResponse;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FirstTest</span> <span class="keyword">implements</span> <span class="title">Controller</span> </span>{</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ModelAndView <span class="title">handleRequest</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception </span>{</span><br><span class="line">        <span class="comment">//ModelAndView 模型和视图</span></span><br><span class="line">        ModelAndView mv = <span class="keyword">new</span> ModelAndView();</span><br><span class="line">        System.out.println(<span class="string">"Do"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//封装对象，放在ModelAndView中。Model</span></span><br><span class="line">        mv.addObject(<span class="string">"msg"</span>,<span class="string">"HelloSpringMVC!"</span>);</span><br><span class="line">        <span class="comment">//封装要跳转的视图，放在ModelAndView中</span></span><br><span class="line">        mv.setViewName(<span class="string">"hello"</span>); <span class="comment">//: /WEB-INF/jsp/hello.jsp</span></span><br><span class="line">        <span class="keyword">return</span> mv;</span><br><span class="line">    }</span><br><span class="line"></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<h2 id="2-2-注解方式实现"><a href="#2-2-注解方式实现" class="headerlink" title="2.2.注解方式实现"></a>2.2.注解方式实现</h2><p>*<em>修改 `springmvc-servlet.xml *</em></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">xml</div></div><figure class="highlight xml"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag"><<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"</span>/></span></span><br><span class="line"><span class="tag"><<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"</span>/></span></span><br><span class="line"></span><br><span class="line">改为：</span><br><span class="line"></span><br><span class="line"><span class="comment"><!-- 让Spring MVC不处理静态资源 --></span></span><br><span class="line"><span class="tag"><<span class="name">mvc:default-servlet-handler</span> /></span></span><br><span class="line"></span><br><span class="line"><span class="comment"><!-- 支持mvc注解驱动在spring中一般采用@RequestMapping注解来完成映射关系要想使@RequestMapping注解生效必须向上下文中注册DefaultAnnotationHandlerMapping和一个AnnotationMethodHandlerAdapter实例这两个实例分别在类级别和方法级别处理。而annotation-driven配置帮助我们自动完成上述两个实例的注入。--></span></span><br><span class="line"><span class="tag"><<span class="name">mvc:annotation-driven</span> /></span></span><br></pre></td></tr></tbody></table></figure></div>

<p><strong>书写实体类</strong></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Controller;</span><br><span class="line"><span class="keyword">import</span> org.springframework.ui.Model;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestMapping;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/HelloController"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloController</span> </span>{</span><br><span class="line"></span><br><span class="line">    <span class="comment">//真实访问地址 : 项目名/HelloController/hello</span></span><br><span class="line">    <span class="meta">@RequestMapping</span>(<span class="string">"/hello"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">sayHello</span><span class="params">(Model model)</span></span>{</span><br><span class="line">        <span class="comment">//向模型中添加属性msg与值，可以在JSP页面中取出并渲染</span></span><br><span class="line">        model.addAttribute(<span class="string">"msg"</span>,<span class="string">"hello,SpringMVC"</span>);</span><br><span class="line">        <span class="comment">//web-inf/jsp/hello.jsp</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">"hello"</span>;</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<h1 id="三、数据处理"><a href="#三、数据处理" class="headerlink" title="三、数据处理"></a>三、数据处理</h1><h2 id="3-1-处理提交数据"><a href="#3-1-处理提交数据" class="headerlink" title="3.1.处理提交数据"></a>3.1.处理提交数据</h2><h3 id="3-1-1-提交时的-url-和参数名一样时"><a href="#3-1-1-提交时的-url-和参数名一样时" class="headerlink" title="3.1.1.提交时的 url 和参数名一样时"></a>3.1.1.提交时的 url 和参数名一样时</h3><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">html</div></div><figure class="highlight html"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://localhost/url?name=xx&age=xx</span><br></pre></td></tr></tbody></table></figure></div>

<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/url"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">hello</span><span class="params">(String name, <span class="keyword">int</span> age)</span></span>{</span><br><span class="line">    System.out.println(name + age);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">"hello"</span>;</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<h3 id="3-1-2-提交时的-url-和参数名不一样时"><a href="#3-1-2-提交时的-url-和参数名不一样时" class="headerlink" title="3.1.2.提交时的 url 和参数名不一样时"></a>3.1.2.提交时的 url 和参数名不一样时</h3><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">html</div></div><figure class="highlight html"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://localhost/url?name=xx</span><br></pre></td></tr></tbody></table></figure></div>

<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/url"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">hello</span><span class="params">(@RequestParam(<span class="string">"name"</span>)</span> String Username)</span>{</span><br><span class="line">    System.out.println(Username);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">"hello"</span>;</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<h3 id="3-1-3-提交一个对象"><a href="#3-1-3-提交一个对象" class="headerlink" title="3.1.3.提交一个对象"></a>3.1.3.提交一个对象</h3><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>{</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> age;</span><br><span class="line">    </span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">html</div></div><figure class="highlight html"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://localhost/url?name=xx&age=xx</span><br></pre></td></tr></tbody></table></figure></div>

<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/url"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">user</span><span class="params">(User user)</span></span>{</span><br><span class="line">    System.out.println(user);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">"hello"</span>;</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<h2 id="3-2-数据显示到前端"><a href="#3-2-数据显示到前端" class="headerlink" title="3.2.数据显示到前端"></a>3.2.数据显示到前端</h2><h3 id="3-2-1-ModelAndView"><a href="#3-2-1-ModelAndView" class="headerlink" title="3.2.1.ModelAndView"></a>3.2.1.ModelAndView</h3><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Controller</span> <span class="keyword">implements</span> <span class="title">Controller</span> </span>{</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ModelAndView <span class="title">handleRequest</span><span class="params">(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)</span> <span class="keyword">throws</span> Exception </span>{</span><br><span class="line">        <span class="comment">//返回一个模型视图对象</span></span><br><span class="line">        ModelAndView mv = <span class="keyword">new</span> ModelAndView();</span><br><span class="line">        mv.addObject(<span class="string">"msg"</span>,<span class="string">"value"</span>);</span><br><span class="line">        mv.setViewName(<span class="string">"test"</span>);</span><br><span class="line">        <span class="keyword">return</span> mv;</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<h3 id="3-2-2-ModelMap"><a href="#3-2-2-ModelMap" class="headerlink" title="3.2.2.ModelMap"></a>3.2.2.ModelMap</h3><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/url"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">hello</span><span class="params">(@RequestParam(<span class="string">"username"</span>)</span> String name, ModelMap model)</span>{</span><br><span class="line">    <span class="comment">//封装要显示到视图中的数据</span></span><br><span class="line">    <span class="comment">//相当于req.setAttribute("name",name);</span></span><br><span class="line">    model.addAttribute(<span class="string">"name"</span>,name);</span><br><span class="line">    System.out.println(name);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">"hello"</span>;</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<h3 id="3-2-3-Model"><a href="#3-2-3-Model" class="headerlink" title="3.2.3.Model"></a>3.2.3.Model</h3><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/url"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">hello</span><span class="params">(@RequestParam(<span class="string">"username"</span>)</span> String name, Model model)</span>{</span><br><span class="line">    <span class="comment">//封装要显示到视图中的数据</span></span><br><span class="line">    <span class="comment">//相当于req.setAttribute("name",name);</span></span><br><span class="line">    model.addAttribute(<span class="string">"msg"</span>,name);</span><br><span class="line">    System.out.println(name);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">"test"</span>;</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<h3 id="3-2-4-对比"><a href="#3-2-4-对比" class="headerlink" title="3.2.4.对比"></a>3.2.4.对比</h3><blockquote>
<ul>
<li>Model 只有寥寥几个方法只适合用于储存数据，简化了新手对于Model对象的操作和理解； </li>
<li>ModelMap 继承了 LinkedMap ，除了实现了自身的一些方法，同样的继承 LinkedMap 的方法和特性；</li>
<li>ModelAndView 可以在储存数据的同时，可以进行设置返回的逻辑视图，进行控制展示层的跳转。</li>
</ul>
</blockquote>
<h3 id="3-2-5-过滤器解决乱码"><a href="#3-2-5-过滤器解决乱码" class="headerlink" title="3.2.5.过滤器解决乱码"></a>3.2.5.过滤器解决乱码</h3><p><strong>在 <code>web.xml</code> 配置</strong></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">xml</div></div><figure class="highlight xml"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag"><<span class="name">filter</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">filter-name</span>></span>encoding<span class="tag">< /<span class="attr">filter-name</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">filter-class</span>></span>org.springframework.web.filter.CharacterEncodingFilter<span class="tag">< /<span class="attr">filter-class</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">init-param</span>></span></span><br><span class="line">        <span class="tag"><<span class="name">param-name</span>></span>encoding<span class="tag">< /<span class="attr">param-name</span>></span></span><br><span class="line">        <span class="tag"><<span class="name">param-value</span>></span>utf-8<span class="tag">< /<span class="attr">param-value</span>></span></span><br><span class="line">    <span class="tag">< /<span class="attr">init-param</span>></span></span><br><span class="line"><span class="tag">< /<span class="attr">filter</span>></span></span><br><span class="line"><span class="tag"><<span class="name">filter-mapping</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">filter-name</span>></span>encoding<span class="tag">< /<span class="attr">filter-name</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">url-pattern</span>></span>/*<span class="tag">< /<span class="attr">url-pattern</span>></span></span><br><span class="line"><span class="tag">< /<span class="attr">filter-mapping</span>></span></span><br></pre></td></tr></tbody></table></figure></div>

<h1 id="四、RestFul"><a href="#四、RestFul" class="headerlink" title="四、RestFul"></a>四、RestFul</h1><h2 id="4-1-概念"><a href="#4-1-概念" class="headerlink" title="4.1.概念"></a>4.1.概念</h2><blockquote>
<ul>
<li>Restful就是一个资源定位及资源操作的风格。不是标准也不是协议，只是一种风格。基于这个风格设计的软件可以更简洁，更有层次，更易于实现缓存等机制。</li>
</ul>
</blockquote>
<h2 id="4-2-功能"><a href="#4-2-功能" class="headerlink" title="4.2.功能"></a>4.2.功能</h2><blockquote>
<ul>
<li>资源：互联网所有的事物都可以被抽象为资源</li>
<li>资源操作：使用POST、DELETE、PUT、GET，使用不同方法对资源进行操作。</li>
<li>分别对应 添加、 删除、修改、查询。</li>
</ul>
</blockquote>
<h2 id="4-3-映射访问路径"><a href="#4-3-映射访问路径" class="headerlink" title="4.3.映射访问路径"></a>4.3.映射访问路径</h2><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/commit/{p1}/{p2}"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">index</span><span class="params">(@PathVariable <span class="keyword">int</span> p1, @PathVariable String p2, Model model)</span></span>{</span><br><span class="line"></span><br><span class="line">    String result = p1+p2;</span><br><span class="line">    <span class="comment">//Spring MVC会自动实例化一个Model对象用于向视图中传值</span></span><br><span class="line">    model.addAttribute(<span class="string">"msg"</span>, <span class="string">"结果："</span>+result);</span><br><span class="line">    <span class="comment">//返回视图位置</span></span><br><span class="line">    <span class="keyword">return</span> <span class="string">"test"</span>;</span><br><span class="line"></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<h2 id="4-4-RequestMapping"><a href="#4-4-RequestMapping" class="headerlink" title="4.4.RequestMapping"></a>4.4.RequestMapping</h2><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping</span>(value = <span class="string">"/url"</span>,method = {RequestMethod.POST})	</span><br><span class="line"><span class="meta">@PostMapping</span></span><br><span class="line"><span class="comment">// 两种都是 Post 方法，独立使用</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@RequestMapping</span>(value = <span class="string">"/url"</span>,method = {RequestMethod.GET})    </span><br><span class="line"><span class="meta">@GetMapping</span></span><br><span class="line"><span class="comment">// 两种都是 Get 方法，独立使用</span></span><br></pre></td></tr></tbody></table></figure></div>

<h1 id="五、拦截器"><a href="#五、拦截器" class="headerlink" title="五、拦截器"></a>五、拦截器</h1><p><strong>书写拦截器</strong></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletRequest;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletResponse;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyInterceptor</span> <span class="keyword">implements</span> <span class="title">HandlerInterceptor</span> </span>{</span><br><span class="line"></span><br><span class="line">    <span class="comment">//在请求处理的方法之前执行</span></span><br><span class="line">    <span class="comment">//如果返回true执行下一个拦截器</span></span><br><span class="line">    <span class="comment">//如果返回false就不执行下一个拦截器</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">preHandle</span><span class="params">(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)</span> <span class="keyword">throws</span> Exception </span>{</span><br><span class="line">        System.out.println(<span class="string">"------------处理前------------"</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    }</span><br><span class="line"></span><br><span class="line">    <span class="comment">//在请求处理方法执行之后执行</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postHandle</span><span class="params">(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)</span> <span class="keyword">throws</span> Exception </span>{</span><br><span class="line">        System.out.println(<span class="string">"------------处理后------------"</span>);</span><br><span class="line">    }</span><br><span class="line"></span><br><span class="line">    <span class="comment">//在dispatcherServlet处理后执行,做清理工作.</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterCompletion</span><span class="params">(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)</span> <span class="keyword">throws</span> Exception </span>{</span><br><span class="line">        System.out.println(<span class="string">"------------清理------------"</span>);</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<p><strong>在 <code>springmvc-servlet.xml</code> 中配置</strong></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">xml</div></div><figure class="highlight xml"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag"><<span class="name">mvc:interceptors</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">mvc:interceptor</span>></span></span><br><span class="line">        <span class="comment"><!--/** 包括路径及其子路径--></span></span><br><span class="line">        <span class="comment"><!--/admin/* 拦截的是/admin/add等等这种 , /admin/add/user不会被拦截--></span></span><br><span class="line">        <span class="comment"><!--/admin/** 拦截的是/admin/下的所有--></span></span><br><span class="line">        <span class="tag"><<span class="name">mvc:mapping</span> <span class="attr">path</span>=<span class="string">"/**"</span>/></span></span><br><span class="line">        <span class="comment"><!--bean配置的就是拦截器--></span></span><br><span class="line">        <span class="tag"><<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"拦截器全路径"</span>/></span></span><br><span class="line">    <span class="tag">< /<span class="attr">mvc:interceptor</span>></span></span><br><span class="line"><span class="tag">< /<span class="attr">mvc:interceptors</span>></span></span><br></pre></td></tr></tbody></table></figure></div>

<h1 id="六、文件"><a href="#六、文件" class="headerlink" title="六、文件"></a>六、文件</h1><h2 id="6-1-上传"><a href="#6-1-上传" class="headerlink" title="6.1.上传"></a>6.1.上传</h2><p><strong>在 <code>pom.xml</code> 导入依赖</strong></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">xml</div></div><figure class="highlight xml"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag"><<span class="name">dependency</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">groupId</span>></span>commons-fileupload<span class="tag">< /<span class="attr">groupId</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">artifactId</span>></span>commons-fileupload<span class="tag">< /<span class="attr">artifactId</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">version</span>></span>1.3.3<span class="tag">< /<span class="attr">version</span>></span></span><br><span class="line"><span class="tag">< /<span class="attr">dependency</span>></span></span><br><span class="line"><span class="comment"><!--servlet-api导入高版本的--></span></span><br><span class="line"><span class="tag"><<span class="name">dependency</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">groupId</span>></span>javax.servlet<span class="tag">< /<span class="attr">groupId</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">artifactId</span>></span>javax.servlet-api<span class="tag">< /<span class="attr">artifactId</span>></span></span><br><span class="line">    <span class="tag"><<span class="name">version</span>></span>4.0.1<span class="tag">< /<span class="attr">version</span>></span></span><br><span class="line"><span class="tag">< /<span class="attr">dependency</span>></span></span><br></pre></td></tr></tbody></table></figure></div>

<p><strong>在 <code>springmvc-servlet.xml</code> 中配置 <code>Java Bean</code></strong></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">xml</div></div><figure class="highlight xml"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"><!--文件上传配置--></span></span><br><span class="line"><span class="tag"><<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"multipartResolver"</span>  <span class="attr">class</span>=<span class="string">"org.springframework.web.multipart.commons.CommonsMultipartResolver"</span>></span></span><br><span class="line">    <span class="comment"><!-- 请求的编码格式，必须和请求页面的pageEncoding属性一致，以便正确读取表单的内容，默认为ISO-8859-1 --></span></span><br><span class="line">    <span class="tag"><<span class="name">property</span> <span class="attr">name</span>=<span class="string">"defaultEncoding"</span> <span class="attr">value</span>=<span class="string">"utf-8"</span>/></span></span><br><span class="line">    <span class="comment"><!-- 上传文件大小上限，单位为字节（10485760=10M） --></span></span><br><span class="line">    <span class="tag"><<span class="name">property</span> <span class="attr">name</span>=<span class="string">"maxUploadSize"</span> <span class="attr">value</span>=<span class="string">"10485760"</span>/></span></span><br><span class="line">    <span class="tag"><<span class="name">property</span> <span class="attr">name</span>=<span class="string">"maxInMemorySize"</span> <span class="attr">value</span>=<span class="string">"40960"</span>/></span></span><br><span class="line"><span class="tag">< /<span class="attr">bean</span>></span></span><br></pre></td></tr></tbody></table></figure></div>

<p><strong>书写实体类</strong></p>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Controller;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestMapping;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestParam;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.multipart.commons.CommonsMultipartFile;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletRequest;</span><br><span class="line"><span class="keyword">import</span> java.io.*;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FileController</span> </span>{</span><br><span class="line">    <span class="comment">//@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象</span></span><br><span class="line">    <span class="comment">//批量上传CommonsMultipartFile则为数组即可</span></span><br><span class="line">    <span class="meta">@RequestMapping</span>(<span class="string">"/upload"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">fileUpload</span><span class="params">(@RequestParam(<span class="string">"file"</span>)</span> CommonsMultipartFile file , HttpServletRequest request) <span class="keyword">throws</span> IOException </span>{</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取文件名 : file.getOriginalFilename();</span></span><br><span class="line">        String uploadFileName = file.getOriginalFilename();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//如果文件名为空，直接回到首页！</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="string">""</span>.equals(uploadFileName)){</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"redirect:/index.jsp"</span>;</span><br><span class="line">        }</span><br><span class="line">        System.out.println(<span class="string">"上传文件名 : "</span>+uploadFileName);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//上传路径保存设置</span></span><br><span class="line">        String path = request.getServletContext().getRealPath(<span class="string">"/upload"</span>);</span><br><span class="line">        <span class="comment">//如果路径不存在，创建一个</span></span><br><span class="line">        File realPath = <span class="keyword">new</span> File(path);</span><br><span class="line">        <span class="keyword">if</span> (!realPath.exists()){</span><br><span class="line">            realPath.mkdir();</span><br><span class="line">        }</span><br><span class="line">        System.out.println(<span class="string">"上传文件保存地址："</span>+realPath);</span><br><span class="line"></span><br><span class="line">        InputStream is = file.getInputStream(); <span class="comment">//文件输入流</span></span><br><span class="line">        OutputStream os = <span class="keyword">new</span> FileOutputStream(<span class="keyword">new</span> File(realPath,uploadFileName)); <span class="comment">//文件输出流</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//读取写出</span></span><br><span class="line">        <span class="keyword">int</span> len=<span class="number">0</span>;</span><br><span class="line">        <span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</span><br><span class="line">        <span class="keyword">while</span> ((len=is.read(buffer))!=-<span class="number">1</span>){</span><br><span class="line">            os.write(buffer,<span class="number">0</span>,len);</span><br><span class="line">            os.flush();</span><br><span class="line">        }</span><br><span class="line">        os.close();</span><br><span class="line">        is.close();</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"redirect:/index.jsp"</span>;</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<h2 id="6-2-下载"><a href="#6-2-下载" class="headerlink" title="6.2.下载"></a>6.2.下载</h2><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping</span>(value=<span class="string">"/download"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">downloads</span><span class="params">(HttpServletResponse response ,HttpServletRequest request)</span> <span class="keyword">throws</span> Exception</span>{</span><br><span class="line">    <span class="comment">//要下载的图片地址</span></span><br><span class="line">    String  path = request.getServletContext().getRealPath(<span class="string">"/upload"</span>);</span><br><span class="line">    String  fileName = <span class="string">"基础语法.jpg"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//1、设置response 响应头</span></span><br><span class="line">    response.reset(); <span class="comment">//设置页面不缓存,清空buffer</span></span><br><span class="line">    response.setCharacterEncoding(<span class="string">"UTF-8"</span>); <span class="comment">//字符编码</span></span><br><span class="line">    response.setContentType(<span class="string">"multipart/form-data"</span>); <span class="comment">//二进制传输数据</span></span><br><span class="line">    <span class="comment">//设置响应头</span></span><br><span class="line">    response.setHeader(<span class="string">"Content-Disposition"</span>,</span><br><span class="line">            <span class="string">"attachment;fileName="</span>+URLEncoder.encode(fileName, <span class="string">"UTF-8"</span>));</span><br><span class="line"></span><br><span class="line">    File file = <span class="keyword">new</span> File(path,fileName);</span><br><span class="line">    <span class="comment">//2、 读取文件--输入流</span></span><br><span class="line">    InputStream input=<span class="keyword">new</span> FileInputStream(file);</span><br><span class="line">    <span class="comment">//3、 写出文件--输出流</span></span><br><span class="line">    OutputStream out = response.getOutputStream();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">byte</span>[] buff =<span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</span><br><span class="line">    <span class="keyword">int</span> index=<span class="number">0</span>;</span><br><span class="line">    <span class="comment">//4、执行 写出操作</span></span><br><span class="line">    <span class="keyword">while</span>((index= input.read(buff))!= -<span class="number">1</span>){</span><br><span class="line">        out.write(buff, <span class="number">0</span>, index);</span><br><span class="line">        out.flush();</span><br><span class="line">    }</span><br><span class="line">    out.close();</span><br><span class="line">    input.close();</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<h1 id="Ajax"><a href="#Ajax" class="headerlink" title="Ajax"></a>Ajax</h1><div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">Javascript</div></div><figure class="highlight js"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">jQuery.ajax(...)</span><br></pre></td></tr></tbody></table></figure></div>

<blockquote>
<ul>
<li>url：请求地址             </li>
<li>type：请求方式，</li>
<li>GET、POST（1.9.0之后用method）          </li>
<li>headers：请求头             </li>
<li>data：要发送的数据     </li>
<li>contentType：即将发送信息至服务器的内容编码类型(默认: “application/x-www-form-urlencoded; charset=UTF-8”)            </li>
<li>async：是否异步          </li>
<li>timeout：设置请求超时时间（毫秒）       </li>
<li>beforeSend：发送请求前执行的函数(全局)         </li>
<li>complete：完成之后执行的回调函数(全局)          </li>
<li>success：成功之后执行的回调函数(全局)            </li>
<li>error：失败之后执行的回调函数(全局)          </li>
<li>accepts：通过请求头发送给服务器，告诉服务器当前客户端课接受的数据类型         </li>
<li>dataType：将服务器端返回的数据转换成指定类型            <ul>
<li>“xml”: 将服务器端返回的内容转换成xml格式           </li>
<li>“text”: 将服务器端返回的内容转换成普通文本格式           </li>
<li>“html”: 将服务器端返回的内容转换成普通文本格式，在插入DOM中时，如果包含JavaScript标签，则会尝试去执行。         </li>
<li>“script”: 尝试将返回值当作JavaScript去执行，然后再将服务器端返回的内容转换成普通文本格式           </li>
<li>“json”: 将服务器端返回的内容转换成相应的JavaScript对象          </li>
<li>“jsonp”: JSONP 格式使用 JSONP 形式调用函数时，如 “myurl?callback=?” jQuery 将自动替换 ? 为正确的函数名，以执行回调函数</li>
</ul>
</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li>在类上直接使用 <strong>@RestController</strong> ，这样子，里面所有的方法都只会返回 json 字符串了，不用再每一个都添加@ResponseBody ！我们在前后端分离开发中，一般都使用 @RestController ，十分便捷！</li>
</ul>
</blockquote>
</body></html></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="mailto:undefined">Cying-承影</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="http://cyingk.github.io/2020/02/16/SpringMVC/">http://cyingk.github.io/2020/02/16/SpringMVC/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/JavaEE/">JavaEE</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2020/02/20/Mybatis/"><img class="prev-cover" src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=575314515,4268715674&amp;fm=26&amp;gp=0.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">MyBatis</div></div></a></div><div class="next-post pull-right"><a href="/2020/02/15/Hibernate/"><img class="next-cover" src="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=607365457,3589909035&amp;fm=26&amp;gp=0.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">Hibernate</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> Related Articles</span></div><div class="relatedPosts-list"><div><a href="/2020/08/06/Linux-And-Docker/" title="SpringCloud With Docker"><img class="cover" src="https://img-blog.csdnimg.cn/202008061653587.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-08-06</div><div class="title">SpringCloud With Docker</div></div></a></div><div><a href="/2020/05/05/SpringCloud/" title="SpringCloud"><img class="cover" src="http://img3.imgtn.bdimg.com/it/u=1799420697,1254911040&fm=26&gp=0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-05-05</div><div class="title">SpringCloud</div></div></a></div><div><a href="/2020/04/05/SpringBoot/" title="SpringBoot"><img class="cover" src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=4157804759,1050439081&fm=26&gp=0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-04-05</div><div class="title">SpringBoot</div></div></a></div><div><a href="/2020/02/20/Mybatis/" title="MyBatis"><img class="cover" src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=575314515,4268715674&fm=26&gp=0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-02-20</div><div class="title">MyBatis</div></div></a></div><div><a href="/2020/02/15/Hibernate/" title="Hibernate"><img class="cover" src="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=607365457,3589909035&fm=26&gp=0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-02-15</div><div class="title">Hibernate</div></div></a></div><div><a href="/2020/02/01/Struts2/" title="Struts2"><img class="cover" src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2597327423,2034793762&fm=26&gp=0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-02-01</div><div class="title">Struts2</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">1.</span> <span class="toc-text">SpringMVC</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%80%E3%80%81MVC-%E6%A6%82%E8%BF%B0"><span class="toc-number">2.</span> <span class="toc-text">一、MVC 概述</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-1-%E4%BB%80%E4%B9%88%E6%98%AF-MVC"><span class="toc-number">2.1.</span> <span class="toc-text">1.1.什么是 MVC</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-2-%E5%AF%BC%E5%85%A5%E4%BE%9D%E8%B5%96"><span class="toc-number">2.2.</span> <span class="toc-text">1.2.导入依赖</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-3-%E7%89%B9%E7%82%B9"><span class="toc-number">2.3.</span> <span class="toc-text">1.3.特点</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-4-%E4%B8%AD%E5%BF%83%E6%8E%A7%E5%88%B6%E5%99%A8"><span class="toc-number">2.4.</span> <span class="toc-text">1.4.中心控制器</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-5-%E5%8E%9F%E7%90%86"><span class="toc-number">2.5.</span> <span class="toc-text">1.5.原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-6-%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B%E5%88%86%E6%9E%90"><span class="toc-number">2.6.</span> <span class="toc-text">1.6.执行流程分析</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E5%85%B7%E4%BD%93%E5%AE%9E%E7%8E%B0"><span class="toc-number">3.</span> <span class="toc-text">二、具体实现</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#2-1-%E5%8E%9F%E5%A7%8B%E6%96%B9%E6%B3%95%E5%AE%9E%E7%8E%B0"><span class="toc-number">3.1.</span> <span class="toc-text">2.1.原始方法实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-2-%E6%B3%A8%E8%A7%A3%E6%96%B9%E5%BC%8F%E5%AE%9E%E7%8E%B0"><span class="toc-number">3.2.</span> <span class="toc-text">2.2.注解方式实现</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%89%E3%80%81%E6%95%B0%E6%8D%AE%E5%A4%84%E7%90%86"><span class="toc-number">4.</span> <span class="toc-text">三、数据处理</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#3-1-%E5%A4%84%E7%90%86%E6%8F%90%E4%BA%A4%E6%95%B0%E6%8D%AE"><span class="toc-number">4.1.</span> <span class="toc-text">3.1.处理提交数据</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-1-%E6%8F%90%E4%BA%A4%E6%97%B6%E7%9A%84-url-%E5%92%8C%E5%8F%82%E6%95%B0%E5%90%8D%E4%B8%80%E6%A0%B7%E6%97%B6"><span class="toc-number">4.1.1.</span> <span class="toc-text">3.1.1.提交时的 url 和参数名一样时</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-2-%E6%8F%90%E4%BA%A4%E6%97%B6%E7%9A%84-url-%E5%92%8C%E5%8F%82%E6%95%B0%E5%90%8D%E4%B8%8D%E4%B8%80%E6%A0%B7%E6%97%B6"><span class="toc-number">4.1.2.</span> <span class="toc-text">3.1.2.提交时的 url 和参数名不一样时</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-3-%E6%8F%90%E4%BA%A4%E4%B8%80%E4%B8%AA%E5%AF%B9%E8%B1%A1"><span class="toc-number">4.1.3.</span> <span class="toc-text">3.1.3.提交一个对象</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-2-%E6%95%B0%E6%8D%AE%E6%98%BE%E7%A4%BA%E5%88%B0%E5%89%8D%E7%AB%AF"><span class="toc-number">4.2.</span> <span class="toc-text">3.2.数据显示到前端</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-1-ModelAndView"><span class="toc-number">4.2.1.</span> <span class="toc-text">3.2.1.ModelAndView</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-2-ModelMap"><span class="toc-number">4.2.2.</span> <span class="toc-text">3.2.2.ModelMap</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-3-Model"><span class="toc-number">4.2.3.</span> <span class="toc-text">3.2.3.Model</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-4-%E5%AF%B9%E6%AF%94"><span class="toc-number">4.2.4.</span> <span class="toc-text">3.2.4.对比</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-5-%E8%BF%87%E6%BB%A4%E5%99%A8%E8%A7%A3%E5%86%B3%E4%B9%B1%E7%A0%81"><span class="toc-number">4.2.5.</span> <span class="toc-text">3.2.5.过滤器解决乱码</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%9B%9B%E3%80%81RestFul"><span class="toc-number">5.</span> <span class="toc-text">四、RestFul</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#4-1-%E6%A6%82%E5%BF%B5"><span class="toc-number">5.1.</span> <span class="toc-text">4.1.概念</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-2-%E5%8A%9F%E8%83%BD"><span class="toc-number">5.2.</span> <span class="toc-text">4.2.功能</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-3-%E6%98%A0%E5%B0%84%E8%AE%BF%E9%97%AE%E8%B7%AF%E5%BE%84"><span class="toc-number">5.3.</span> <span class="toc-text">4.3.映射访问路径</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-4-RequestMapping"><span class="toc-number">5.4.</span> <span class="toc-text">4.4.RequestMapping</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%94%E3%80%81%E6%8B%A6%E6%88%AA%E5%99%A8"><span class="toc-number">6.</span> <span class="toc-text">五、拦截器</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%AD%E3%80%81%E6%96%87%E4%BB%B6"><span class="toc-number">7.</span> <span class="toc-text">六、文件</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#6-1-%E4%B8%8A%E4%BC%A0"><span class="toc-number">7.1.</span> <span class="toc-text">6.1.上传</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-2-%E4%B8%8B%E8%BD%BD"><span class="toc-number">7.2.</span> <span class="toc-text">6.2.下载</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Ajax"><span class="toc-number">8.</span> <span class="toc-text">Ajax</span></a></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="footer_custom_text">却道天凉好个秋</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="Increase font size"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="Decrease font size"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script></div><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>